<template>
  <el-card>
    <div>
      <el-input
        prefix-icon="el-icon-search"
        class="width40"
        v-model.trim="keyword"
        @keyup.native.enter="getRoleList(1, undefined, undefined, $event)"
      ></el-input>
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="getRoleList(1, undefined, undefined, $event)"
        >查询</el-button
      >
      <el-button @click="clearKeyword">清空</el-button>
    </div>
    <div class="top10">
      <el-form>
        <el-form-item label="角色名称">
          <el-input
            class="width40"
            v-model.trim="form.roleName"
            autocomplete
            autofocus
            @keyup.native.enter="addRoleInfo"
          ></el-input>
          <el-button type="primary" @click="addRoleInfo">添加角色</el-button>
        </el-form-item>
      </el-form>
      <el-button
        type="danger"
        size="mini"
        title="批量删除"
        icon="el-icon-delete"
        @click="batchDelRole"
        :disabled="this.batchRoleIds.length == 0"
      ></el-button>
    </div>
    <div>
      <el-table
        border
        height="60vh"
        :data="roleInfoList"
        @selection-change="selectRole"
      >
        <el-table-column
          label=""
          type="selection"
          align="center"
        ></el-table-column>
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column label="角色名称" prop="">
          <template #default="{ row, $index }">
            <span title="编辑模式下,按下回车可执行更改" v-if="!row.flag">{{
              row.roleName
            }}</span>
            <el-input
              size="mini"
              :ref="$index"
              class="width40"
              v-model.trim="row.temp_roleName"
              v-else
              title="编辑模式下,按下回车可执行更改"
              @keyup.native.enter="updateRoleInfo(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button
              size="mini"
              icon="el-icon-info"
              type=""
              title="查看角色权限"
              @click="lookRoleAuth(row)"
            ></el-button>
            <el-button
              size="mini"
              icon="el-icon-info"
              type="info"
              title="编辑角色权限"
              @click="editRoleAuth(row)"
            ></el-button>
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="warning"
              title="编辑角色名称"
              v-show="!row.flag"
              @click="editRoleName($index, row)"
            ></el-button>
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="success"
              title="取消编辑角色名称"
              v-show="row.flag"
              @click="row.flag = false"
            ></el-button>
            <el-popconfirm
              title="确认删除吗?"
              @onConfirm="delRoleInfo(row.id)"
              style="margin-left: 10px"
            >
              <template #reference>
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  title="删除角色"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <!-- 分页 -->
      </el-table>
      <el-pagination
        @current-change="getRoleList2($event)"
        @size-change="getRoleList2(undefined, $event)"
        class="center"
        :total="totalPage"
        :current-page="curPage"
        :page-size="limitNum"
        :page-sizes="[5, 10, 20, 30]"
        layout="sizes, prev, pager, next, jumper, ->, total, slot"
      ></el-pagination>
    </div>
    <!-- 查看角色权限 -->
    <div>
      <el-drawer
        size="30%"
        :visible.sync="showDrawer"
        direction="rtl"
        :show-close="false"
      >
        <template #title>
          <el-card>
            <h3 class="center">{{ curLookRole }} 的权限:</h3>
          </el-card>
        </template>
        <el-card class="height100">
          <el-tree
            :data="roleAuthList"
            :props="defaultProps"
            :default-expand-all="false"
          ></el-tree>
        </el-card>
      </el-drawer>
    </div>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      // 批量删除
      batchRoleIds: [],
      // 查看角色权限
      defaultProps: { children: 'children', label: 'name' }, //对应字段
      showDrawer: false,
      curLookRole: '',
      roleAuthList: [],
      // 添加角色
      form: {
        id: undefined,
        roleName: ''
      },
      // 搜索
      keyword: '',
      // 分页
      curPage: 1,
      totalPage: 0,
      limitNum: 10,
      roleInfoList: []
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (val.path.indexOf('role/list') != -1) {
          const { page = '', limit = '', keyword = '' } = this.$route.query
          this.getRoleList(page, limit, keyword)
        }
      },
      immediate:true
    }
  },
  methods: {
    selectRole(rowList) {
      this.batchRoleIds = rowList.map((item) => item.id)
    },
    // 批量删除
    batchDelRole() {
      if (this.batchRoleIds.length == 0) {
        return
      }
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          const res = await this.$API.role.batchDelRole(this.batchRoleIds)
          if (res.ok) {
            this.$message({ type: 'success', message: '删除成功' })
            this.getRoleList()
          } else {
            this.$message({
              type: 'error',
              message: res.message + ':' + (res.data || '')
            })
          }
        })
        .catch(() => {})
    },
    // 编辑角色权限
    editRoleAuth(row) {
      // 路由跳转
      this.$router.push({
        name: 'RoleAuth',
        params: { roleId: row.id },
        query: {
          roleName: row.roleName,
          redirect: `/acl/role/list?page=${this.curPage}&limit=${this.limitNum}`
        }
      })
    },
    // 查看角色权限
    async lookRoleAuth(row) {
      const res = await this.$API.role.getRoleJurisdiction(row.id)
      if (res.ok) {
        this.roleAuthList = res.data.children[0].children.filter(
          (item) => item.select
        )
        // 显示对话框
        this.curLookRole = row.roleName
        this.showDrawer = true
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 删除角色
    async delRoleInfo(id) {
      const res = await this.$API.role.delRoleInfo(id)
      if (res.ok) {
        this.$message({ type: 'success', message: '删除成功' })
        this.getRoleList()
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 跟新角色
    updateRoleInfo(row) {
      if (row.temp_roleName) {
        this.form.id = row.id
        this.form.roleName = row.temp_roleName
        this.addRoleInfo()
        // 隐藏input
        row.flag = false
      } else {
        this.$message({ type: 'warning', message: '输入为空' })
      }
    },
    editRoleName(ref_index, row) {
      // 切换input
      row.flag = true
      // input渲染好了
      this.$nextTick(() => {
        this.$refs[ref_index].focus()
      })
    },
    // 添加角色
    async addRoleInfo(event) {
      if (this.form.roleName) {
        const res = await this.$API.role.addOrupdataRoleInfo(this.form)
        if (res.ok) {
          this.$message({
            type: 'success',
            message: this.form.id ? '修改成功' : '添加成功'
          })
          // 清空数据
          this.form.id = undefined
          this.form.roleName = ''
          // 跟新数据
          this.getRoleList()
        } else {
          this.$message({
            type: 'error',
            message: res.message + ':' + (res.data || '')
          })
        }
      } else {
        this.$message({ type: 'warning', message: '请输入角色名' })
      }
    },
    clearKeyword() {
      this.keyword = ''
      this.getRoleList(1)
    },
    // 页面改变,路由跳转本身
    getRoleList2(page, limit, keyword = this.keyword) {
      if (page) {
        this.curPage = parseInt(page)
      }
      if (limit) {
        this.limitNum = parseInt(limit)
      }
      this.$router.push({
        name: 'Role',
        query: { page: this.curPage, limit: this.limitNum, keyword }
      })
    },

    //获取分页列表
    async getRoleList(page, limit, keyword = this.keyword) {
      if (page) {
        this.curPage = parseInt(page)
      }
      if (limit) {
        this.limitNum = parseInt(limit)
      }

      const res = await this.$API.role.getRoleList(
        this.curPage,
        this.limitNum,
        keyword
      )
      if (res.ok) {
        this.totalPage = res.data.total
        res.data.items.forEach((item) => {
          item['temp_roleName'] = item.roleName
          item['flag'] = false
          // this.roleInfoList.push(item)
          // 使用push之前要考虑清空上次的数据
        })
        this.roleInfoList = res.data.items
      } else {
      }
    }
  },
  created() {
    // this.getRoleList()
  }
}
</script>

<style>
.center {
  text-align: center;
}

.width40 {
  width: 40%;
}

.top10 {
  margin-top: 10px;
}

.center {
  text-align: center;
}

.height100 {
  height: 100vh;
}

.scroll {
  overflow: auto;
}

</style>
